const express = require('express');
const router = express.Router();
const _ = require('lodash');

const helper = require('../../util/helper');
const userService  = require("../../services/admin/userService");

module.exports = router;

/* GET users listing. */
router.get('/', (req, res, next) => {
    res.render('admin/user', {
        user: req.session.user,
        menus: req.session.menus,
        menu_active: req.session.menu_active['/users'] || {},
        title: '用户管理'
    });
});

router.get('/load', async(req, res, next) => {
    var name = req.query.s_name;
    var username = req.query.s_user_name;
    var start = req.query.start;
    var length = req.query.length;
    var draw = req.query.draw;

    if (!start || !draw || !length) {
        res.status(401).json("invoke error!");
        return;
    }

    start  = parseInt(start) || 0;
    length = parseInt(length) || 0;
    draw   = parseInt(draw) || 0;
    name   = name?name.trim():null;
    username = username?username.trim():null;

    userService.getUsers(name, username, start, length, function (err, data) {
        if (!!err){
            return res.status(200).json({error:err.errCode, msg:err.message});
        }

        var result = { draw: draw, recordsTotal: data.count, recordsFiltered: data.count, data: [] };
        data.rows.forEach(function (user) {
            result.data.push(user.toParams());
        });

        return res.status(200).json(result);
    });
});

router.get('/save', async(req, res, next) => {
    var user = req.session.user;
    var {e_id, e_user_name, e_name, e_birthday, e_phone, e_sex, e_mail, e_password} = req.query;
    if (e_user_name.trim() == "") {
        return res.status(200).json({error: 1, msg: "登录名不能为空"});
    }

    if (e_name.trim() == "") {
        return res.status(200).json({error: 1, msg: "用户名称不能为空"});
    }

    if (e_id == "" && (!e_password || e_password.trim() == "")) {
        return res.status(200).json({error: 1, msg: "密码不能为空"});
    }

    if (e_birthday.trim() == "") {
        return res.status(200).json({error: 1, msg: "生日不能为空"});
    }

    if (e_phone.trim() == "") {
        return res.status(200).json({error: 1, msg: "手机号不能为空"});
    }

    if (e_mail.trim() == "") {
        return res.status(200).json({error: 1, msg: "邮箱不能为空"});
    }

    if (e_id) {
        const updateParams = {
            id: e_id,
            user_name: e_user_name.trim(),
            name: e_name.trim(),
            tel: e_phone.trim(),
            birthday: e_birthday.trim(),
            sex: e_sex.trim(),
            mail: e_mail.trim(),
            modified_id: user.id,
            modified_at: new Date()
        };

        if (e_password){
            updateParams.password = e_password.trim();
        }

        userService.updateUser(updateParams, async function (err, result) {
            if (!!err) {
                return res.status(200).json({error:err.errCode, msg:err.message});
            }

            await helper.saveOpLog(user.id, user.user_name, user.name, "更新用户："+e_name+";ID: "+e_id);
            res.status(200).json({error: 0, msg: "用户信息更新成功"});
        });
    } else {
        const userInfo = {
            user_name: e_user_name.trim(),
            name: e_name.trim(),
            tel: e_phone.trim(),
            birthday: e_birthday.trim(),
            sex: e_sex.trim(),
            mail: e_mail.trim(),
            password: e_password.trim(),
            creator_id: user.id,
            created_at: new Date(),
            modified_id: user.id,
            modified_at: new Date()
        };

        userService.createUser(userInfo, async function (err, newUser) {
            if (!!err) {
                return res.status(200).json({error:err.errCode, msg:err.message});
            }

            await helper.saveOpLog(user.id, user.user_name, user.name, "新增用户："+e_name);
            res.status(200).json({error: 0, msg: "新增用户成功"});
        });
    }
});

router.delete('/delete', async(req, res, next) => {
    var ids = req.body.ids, user = req.session.user;
    if (!ids || ids.trim().length == 0) {
        res.status(200).json({error: 1, msg: '删除失败，必须选择一项'});
    }

    ids = ids.trim().split(",");
    if (_.indexOf(ids, user.id+'') != -1) {
        res.status(200).json({error: 1, msg: '不能删除自己'});
    }

    userService.destroyUsers(ids, async function (err, result) {
        if (!!err){
            return res.status(200).json({error: 1, msg: '删除失败，请联系管理员'});
        }

        await helper.saveOpLog(user.id, user.user_name, user.name, "删除用户ID: " + ids.join(','));
        return res.status(200).json({error: 0, msg: "用户删除成功"});
    });
});
